"use client";

import { ClerkProvider, useAuth } from "@clerk/nextjs";
import { ConvexProviderWithClerk } from "convex/react-clerk";
import { AuthLoading, Authenticated, ConvexReactClient } from "convex/react";
import Loading from "@/components/auth/loading";

interface ConvexClientProviderProps {
  children: React.ReactNode;
}

const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL!;

const convex = new ConvexReactClient(convexUrl as string);

export const ConvexClientProvider = ({
  children,
}: ConvexClientProviderProps) => {
  return (
    <ClerkProvider>
      {/* ConvexProviderWithClerk 是Convex和Clerk集成的一个提供器组件，它允许你的应用程序与 Convex 的后端服务进行通信，并且结合 Clerk 的身份验证功能 */}
      <ConvexProviderWithClerk client={convex} useAuth={useAuth}>
        {/* Authenticated 确保子组件仅在用户通过身份验证后渲染 */}
        <Authenticated>{children}</Authenticated>
        {/* AuthLoading 身份验证过程中显示加载状态 */}
        <AuthLoading>
          <Loading></Loading>
        </AuthLoading>
      </ConvexProviderWithClerk>
    </ClerkProvider>
  );
};
